import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Modal, message, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import DataTable from '../../../components/common/DataTable';
import { useNavigate } from 'react-router-dom';
import { listSalaries, deleteSalary } from '../../../api/salary';

// 移除模拟数据导入
// import { mockSalaries } from '../../../mock/mockData';

const { confirm } = Modal;

const SalaryList = () => {
    const navigate = useNavigate();
    const [loading, setLoading] = useState(false);
    const [dataSource, setDataSource] = useState([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    });

    // 状态常量
    const STATUS_MAP = {
        0: '未发放',
        1: '已发放'
    };

    useEffect(() => {
        fetchSalaries();
    }, [pagination.current, pagination.pageSize]);

    // 获取薪资数据
    const fetchSalaries = async () => {
        setLoading(true);
        try {
            // 使用实际API接口获取数据
            const response = await listSalaries({
                page: pagination.current,
                pageSize: pagination.pageSize
            });
            
            setDataSource(response.data || []);
            setPagination({
                ...pagination,
                total: response.total || 0
            });
        } catch (error) {
            console.error('获取薪资列表失败:', error);
            message.error('获取薪资列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 处理表格变化
    const handleTableChange = (pagination) => {
        setPagination(pagination);
    };

    // 处理搜索
    const handleSearch = async (value) => {
        setLoading(true);
        try {
            const response = await listSalaries({
                page: 1,
                pageSize: pagination.pageSize,
                keyword: value
            });
            
            setDataSource(response.data || []);
            setPagination({
                ...pagination,
                current: 1,
                total: response.total || 0
            });
        } catch (error) {
            console.error('搜索薪资记录失败:', error);
            message.error('搜索薪资记录失败');
        } finally {
            setLoading(false);
        }
    };

    // 处理添加薪资记录
    const handleAdd = () => {
        navigate('/salary/add');
    };

    // 处理编辑薪资记录
    const handleEdit = (record) => {
        navigate(`/salary/edit/${record.id}`);
    };

    // 处理删除薪资记录
    const handleDelete = (record) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined />,
            content: '确定要删除该薪资记录吗？',
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
                try {
                    // 调用删除API
                    await deleteSalary(record.id);
                    message.success('删除成功');
                    fetchSalaries(); // 重新加载数据
                } catch (error) {
                    console.error('删除薪资记录失败:', error);
                    message.error('删除失败');
                }
            }
        });
    };

    // 表格列定义
    const columns = [
        {
            title: '员工姓名',
            dataIndex: ['employee', 'name'],
            key: 'employeeName',
            width: 100
        },
        {
            title: '年份',
            dataIndex: 'year',
            key: 'year',
            width: 80
        },
        {
            title: '月份',
            dataIndex: 'month',
            key: 'month',
            width: 80
        },
        {
            title: '基本工资',
            dataIndex: 'base_salary',
            key: 'baseSalary',
            width: 100,
            render: (text) => `¥${parseFloat(text).toLocaleString()}`
        },
        {
            title: '奖金',
            dataIndex: 'bonus',
            key: 'bonus',
            width: 100,
            render: (text) => `¥${parseFloat(text).toLocaleString()}`
        },
        {
            title: '加班费',
            dataIndex: 'overtime',
            key: 'overtime',
            width: 100,
            render: (text) => `¥${parseFloat(text).toLocaleString()}`
        },
        {
            title: '补贴',
            dataIndex: 'allowance',
            key: 'allowance',
            width: 100,
            render: (text) => `¥${parseFloat(text).toLocaleString()}`
        },
        {
            title: '扣除',
            dataIndex: 'deduction',
            key: 'deduction',
            width: 100,
            render: (text) => `¥${parseFloat(text).toLocaleString()}`
        },
        {
            title: '实发工资',
            dataIndex: 'net_salary',
            key: 'netSalary',
            width: 100,
            render: (text) => `¥${parseFloat(text).toLocaleString()}`
        },
        {
            title: '发放日期',
            dataIndex: 'payment_date',
            key: 'paymentDate',
            width: 120
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 100,
            render: (status) => (
                <Tag color={status === 1 ? 'green' : 'orange'}>
                    {STATUS_MAP[status]}
                </Tag>
            )
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            width: 150
        },
        {
            title: '操作',
            key: 'action',
            width: 120,
            render: (_, record) => (
                <Space>
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button
                        type="link"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleDelete(record)}
                    >
                        删除
                    </Button>
                </Space>
            )
        }
    ];

    return (
        <Card
            title="薪资列表"
            extra={
                <Space>
                    <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={handleAdd}
                    >
                        添加薪资记录
                    </Button>
                </Space>
            }
        >
            <DataTable
                loading={loading}
                columns={columns}
                dataSource={dataSource}
                pagination={pagination}
                onChange={handleTableChange}
                onSearch={handleSearch}
                rowKey="id"
                scroll={{ x: 1500 }}
            />
        </Card>
    );
};

export default SalaryList;